const fetch = require('node-fetch')
const domain = 'http://localhost:8000'
const authKey = 'Bearer testtesttest'
const api = {};

let apiCount = 0; // 临时接口计数器

api.api_fetch = function (url, method, body, cbk, errorCallBack) {
	const options = {
		method: method ? method : 'GET',
		headers: {
			'authorization': authKey,
			'Content-Type': 'application/json;charset=UTF-8'
		}
	};
	if (body) {
		options['body'] = JSON.stringify(body)
	}
	// console.log((++apiCount) + ':' + url);
	// console.log(domain);
	// console.log(options);
	// console.time('api run times');
	fetch(domain + url, options)
		.then(function (res) {
			if (res.status !== 200 && res.message) {
				errorCallBack && errorCallBack(res)
				return;
			}
			return res.text();
		})
		.then(function (json) {
			if (!json) {
				return;
			}
			const jsonRes = jsonParse(json);
			if (typeof jsonRes === 'object' && jsonRes.status && jsonRes.status !== 200) {
				errorCallBack && errorCallBack(jsonRes);
				return;
			}
			cbk && cbk(jsonRes);
		})
		.catch(error => {
			errorCallBack && errorCallBack(error)
		}).finally(() => {
			// console.timeEnd('api run times');
		})
}
api.api_get = function (url, params, cbk, errorCallBack) {
	if (params) {
		let paramsArray = [];
		//拼接参数
		Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
		if (url.search(/\?/) === -1) {
			url += '?' + paramsArray.join('&')
		} else {
			url += '&' + paramsArray.join('&')
		}
	}
	api.api_fetch(url, 'GET', undefined, cbk, errorCallBack);
}
api.api_post = function (url, body, cbk, errorCallBack) {
	api.api_fetch(url, 'POST', body, cbk, errorCallBack);
}
api.api_put = function (url, body, cbk, errorCallBack) {
	api.api_fetch(url, 'PUT', body, cbk, errorCallBack);
}
api.api_post_formdata = (url, body, headers = {}, cbk, errorCallBack) => {
    const options = {
		method: 'POST',
		headers: {
            ...headers,
			'authorization': authKey
		},
        body,
	};
	fetch(domain + url, options)
		.then(function (res) {
            console.log('res', res)
			if (res.status !== 200) {
				errorCallBack && errorCallBack(res)
				return;
			}
			return res.text();
		})
		.then(function (json) {
			if (!json) {
				return;
			}
			cbk && cbk(jsonParse(json));
		})
		.catch(error => {
			errorCallBack && errorCallBack(error)
		})
}
api.api_put_formdata = (url, body, headers = {}, cbk, errorCallBack) => {
    const options = {
		method: 'PUT',
		headers: {
            ...headers,
			'authorization': authKey
		},
        body,
	};
	fetch(domain + url, options)
		.then(function (res) {
            // console.log('res', res)
			if (res.status !== 200) {
				errorCallBack && errorCallBack(res)
				return;
			}
			return res.text();
		})
		.then(function (json) {
			if (!json) {
				return;
			}
			cbk && cbk(jsonParse(json));
		})
		.catch(error => {
			errorCallBack && errorCallBack(error)
		})
}

api.api_fetch_async = async function (url, method, body){
	return new Promise((resolve, reject) => {
		api.api_fetch(url, method, body, res => {
			resolve(res)
		}, err => {
			reject(err)
		})
	})
}
api.api_get_async = async function (url, params) {
	if (params) {
		let paramsArray = [];
		//拼接参数
		Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
		if (url.search(/\?/) === -1) {
			url += '?' + paramsArray.join('&')
		} else {
			url += '&' + paramsArray.join('&')
		}
	}
	return api.api_fetch_async(url, 'GET', undefined)
}
api.api_post_async = async function (url, body) {
	return api.api_fetch_async(url, 'POST', body)
}
api.api_put_async = async function (url, body) {
	return api.api_fetch_async(url, 'PUT', body)
}
api.api_post_formdata_async = async (url, body, headers) => {
	return new Promise((resolve, reject) => {
		api.api_post_formdata(url, body, headers, res => {
			resolve(res)
		}, err => {
			reject(err)
		})
	})
}
api.api_put_formdata_async = async (url, body, headers) => {
	return new Promise((resolve, reject) => {
		api.api_put_formdata(url, body, headers, res => {
			resolve(res)
		}, err => {
			reject(err)
		})
	})
}
function jsonParse(str) {
	try {
		const res = JSON.parse(str)
		if (typeof res == "object") {
			return res;
		}
	} catch (e) {
	}
	return str;
}

module.exports = api;
